﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PDFLibNet;

namespace Htm2Pdf.Convertor
{
    public class ThumbGenerator
    {
        public static void Generate(string inputPdf, string outputImage)
        {
            PDFWrapper dc = new PDFWrapper();
            dc.LoadPDF(inputPdf);
            

            Image img = RenderPage(dc, 0);

            Image resizedImg = ResizeImage(img);


            resizedImg.Save(outputImage, System.Drawing.Imaging.ImageFormat.Png);

        }

        private static Image ResizeImage(Image img)
        {
            float percentage = 0.3f;

            //get the height and width of the image
            int originalW = img.Width;
            int originalH = img.Height;

            //get the new size based on the percentage change
            int resizedW = (int)(originalW * percentage);
            int resizedH = (int)(originalH * percentage);

            //create a new Bitmap the size of the new image
            Bitmap bmp = new Bitmap(resizedW, resizedH);
            //create a new graphic from the Bitmap
            Graphics graphic = Graphics.FromImage((Image)bmp);
            graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
            //draw the newly resized image
            graphic.DrawImage(img, 0, 0, resizedW, resizedH);
            //dispose and free up the resources
            graphic.Dispose();
            //return the image
            return (Image)bmp;
        }


        private static Image RenderPage(PDFWrapper doc, int page)
        {
            doc.CurrentPage = page + 1;
            doc.CurrentX = 0;
            doc.CurrentY = 0;

            using (var box = new PictureBox())
            {
                // have to give the document a handle to render into
                doc.RenderPage(box.Handle);

                // create an image to draw the page into
                var buffer = new Bitmap(doc.PageWidth, doc.PageHeight);
                doc.ClientBounds = new Rectangle(0, 0, doc.PageWidth, doc.PageHeight);
                using (var g = Graphics.FromImage(buffer))
                {
                    var hdc = g.GetHdc();
                    try
                    {
                        doc.DrawPageHDC(hdc);
                    }
                    finally
                    {
                        g.ReleaseHdc();
                    }
                }

                return buffer;
            }
        }
    }
}
